<template>
  <div>
    <!-- 所搜条件 -->
    <div class="search-div" style="margin-top: 20px;">
      <el-form label-width="70px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="关 键 字">
              <el-input style="width: 95%" v-model="searchObj.keyword" placeholder="用户名/姓名/手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间">
              <el-date-picker v-model="createTimes" type="datetimerange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" style="margin-right: 10px;width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button type="primary" plain icon="el-icon-search" @click="userListPage()">搜索</el-button>
            <el-button type="success" plain icon="el-icon-refresh-left" @click="reset()">重置</el-button>
            <el-button type="danger" plain icon="el-icon-document-add" :disabled="$hasBP('bnt.sysRole.add')  === false"  @click="addBtn()">添加</el-button>
            <el-button type="danger" plain icon="el-icon-document-add" :disabled="$hasBP('bnt.sysRole.batchRemove')  === false" @click="batchRemove()">批量删除</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="list" border style="width: 100%;margin-top: 10px;"
      :row-class-name="tableRowClassName" :header-cell-style="getRowClass" @selection-change="handleSelectionChange">
      <!-- 复选框 -->
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名称" />
      <el-table-column prop="name" label="真实姓名" />
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="description" label="用户描述" />
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status === 1" @change="switchStatus(scope.row)" active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="350" />
      <el-table-column prop="updateTime" label="修改时间" width="350" />
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" :disabled="$hasBP('bnt.sysRole.update')  === false" @click="edit(scope.row)" title="修改" />
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="$hasBP('bnt.sysRole.remove')  === false" @click="removeDataById(scope.row)" title="删除" />
          <el-button type="warning" icon="el-icon-baseball" size="mini" @click="showAssignRole(scope.row)" title="分配角色"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination background @current-change="currentChange" @size-change="sizeChange" :page-sizes="[5, 10, 15, 20]"
        :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
        style="padding: 30px 0; text-align: center;">
      </el-pagination>
    </div>
    <!-- 新增角色弹出框 -->
    <el-dialog title="添加 或者 修改" :visible.sync="dialogVisible" width="30%">
      <el-form :model="sysUser" :rules="rules" ref="sysUser" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="sysUser.username"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="sysUser.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="sysUser.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="sysUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="sysUser.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRole(sysRole)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色弹出框 -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="sysUser.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="assignRole" size="small">保存</el-button>
        <el-button @click="dialogRoleVisible = false" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/system/sysUser/sys-user'
import { logicalExpression, thisTypeAnnotation } from '@babel/types';


const defaultForm = {
        username: '',
        password: '',
        name: '',
        phone: '',
        description: '',
      }

export default {
  data() {
    return {
      listLoading: true, //加载动画
      list: [],//数据是否加载
      total: 0, //数据总数
      page: 1,  //页码
      limit: 5, //当前页显示数量
      searchObj: {},  //搜索对象
      sysUser: defaultForm,  //User对象
      createTimes: [],   //存储时间
      multipleSelection: [], //复选框选中列
      dialogVisible: false,  //弹出框状态
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度必须为11个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入用户描述', trigger: 'blur' },
        ]
      },
      dialogRoleVisible:false,  //控制角色分配弹出框
      allRoles: [], // 所有角色列表
      userRoleIds: [], // 用户的角色ID的列表
      isIndeterminate: false, // 是否是不确定的
      checkAll: false // 是否全选
    }
  },
  created() {
    this.userListPage();
  },
  methods: {
    // 接收开发状态变化的值
    switchStatus(obj) {
      obj.status = obj.status === 1 ? 0 : 1
      api.updateStatus(obj.id, obj.status).then(res => {
        if (obj.status === 0) {
          this.$message.warning(res.message)
          return;
        }
        this.$message.success(res.message)
      })
    },
    //分页获取数据
    userListPage() {
      if (this.createTimes && this.createTimes.length === 2) {
        this.searchObj.createTimeBegin = this.createTimes[0]
        this.searchObj.createTimeEnd = this.createTimes[1]
      }
      api.getRoleListPage(this.page, this.limit, this.searchObj)
        .then(res => {
          this.total = res.data.total
          this.list = res.data.records
          this.listLoading = false
        })
    },
    // 表格颜色设置
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 3 === 0) {
        return 'warning-row';
      } else if (rowIndex % 3 === 1) {
        return 'success-row';
      } else {
        return 'default-row';
      }
    },
    // 设置表头颜色
    getRowClass({ row, rowIndex }) {
      return "background:#f8f8f9;";
    },
    // 分页参数变化
    sizeChange(size) {
      this.limit = size
      this.userListPage()
    },
    // 分页参数变化
    currentChange(current) {
      this.page = current;
      this.userListPage();
    },
    // 重置
    reset() {
      this.searchObj = {}
      this.userListPage()
      this.createTimes = []
    },
    //添加用户  --> 弹出角色框
    addBtn() {
      this.sysUser =defaultForm
      this.dialogVisible = true;
    },
    // 批量删除
    batchRemove() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择需要删除的至少一列")
        return;
      }
      this.$confirm('此操作将永久删除数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        this.multipleSelection.forEach(user => {
          ids.push(user.id)
        })
        api.batchRemoveUser(ids).then(res => {
          this.userListPage()
          this.$message.success(res.message || "删除成功")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取到多选框的选中列
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    // 删除
    removeDataById(row) {
      this.$confirm('此操作将永久删除  ' + row.name + ' 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.removeUserById(row.id).then(res => {
          this.userListPage()
          this.$message.success(res.message || "删除成功")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 新增或者修改
    submitRole(sysUser) {
      if (!this.sysUser.id) {
        this.$refs.sysUser.validate((valid) => {
          api.saveUser(this.sysUser).then(res => {
            this.dialogVisible = false;
            this.userListPage();
            this.$message.success(res.message || "添加成功")
          })
        })
        // 结束方法
        return;
      }
      // 修改
      api.updateUser(this.sysUser).then(res => {
        this.dialogVisible = false;
        this.userListPage();
        this.$message.success(res.message || "修改成功")
      })
    },
    // 点击修改，获取最新的用户信息
    edit(row) {
      api.getUserById(row.id).then(res => {
        this.sysUser = res.data;
      })
      this.dialogVisible = true;
    },
    // 弹出角色分配框
    showAssignRole(rowObj){
      this.sysUser.username = rowObj.username;
      this.sysUser.id = rowObj.id
      this.dialogRoleVisible=true;
      api.getRolesByUserId(rowObj.id).then(res=>{
        this.allRoles = res.data.allRoles;
        this.userRoleIds = res.data.userRoleIds;
        this.checkAll = this.userRoleIds.length === this.allRoles
        this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length
      })
    },
    // 监听全部多选框状态
    handleCheckAllChange(value){
      // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
      this.userRoleIds = value?this.allRoles.map(item => item.id):[]
       // 如果当前不是全选也不是全不选时, 指定为false
      this.isIndeterminate=false
    },
    // 监听单个选择框状态
    handleCheckedChange(value){
      // 相当于 userRoleIds = this.userRoleIds;
      // 相当于 allRoles = this.allRoles;
      const {userRoleIds, allRoles} = this
      this.checkAll = userRoleIds.length === allRoles.length && allRoles.length>0
      this.isIndeterminate = userRoleIds.length>0 && userRoleIds.length<allRoles.length
    },
    // 分配角色
    assignRole(){
        const assginRoleVo = {
          userId:this.sysUser.id,
          roleIdList:this.userRoleIds
        }
      api.saveUserRoles(assginRoleVo).then(res=>{
       this.$message.success(res.message || "权限分配成功")
       this.dialogRoleVisible = false;
       this.userListPage();
      })
    }

  }
}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.el-table .default-row {
  background: #F0FFF0;
}
</style>